package com.ruoyi.web.controller.common;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.client.WeChatClient;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.vo.WeChatPhoneNumberResponse;
import com.ruoyi.common.vo.WeChatTokenResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;


/**
 * 微信接口
 * 
 * @author zhangcunlei
 */
@RestController
@RequestMapping("/wechat")
public class WeChatController extends BaseController {

    @Resource
    private WeChatClient weChatClient;

    @Autowired
    private RedisCache redisCache;

    /**
     * 获取微信token
     */
    @GetMapping("/getAccessToken")
    public AjaxResult getAccessToken(@RequestParam String grantType, @RequestParam String appid, @RequestParam String secret) {
        String weChatTokenKey = CacheConstants.WE_CHAT_TOKEN_KEY;
        String tokenValue = redisCache.getCacheObject(weChatTokenKey);
        WeChatTokenResponse weChatClientAccessToken = null;
        if (StringUtils.isBlank(tokenValue)) {
            weChatClientAccessToken = weChatClient.getAccessToken(grantType, appid, secret);
            redisCache.setCacheObject(weChatTokenKey, JSON.toJSONString(weChatClientAccessToken), weChatClientAccessToken.getExpires_in(), TimeUnit.SECONDS);
        } else {
            weChatClientAccessToken = JSON.parseObject(tokenValue, WeChatTokenResponse.class);
        }
        return success(weChatClientAccessToken);
    }

    /**
     * 微信小程序获取手机号
     */
    @PostMapping("/getPhoneNumber")
    public AjaxResult getPhoneNumber(@RequestParam(value = "code") String code,
                                     @RequestParam(value = "accessToken") String accessToken) {
        WeChatPhoneNumberResponse phoneNumber = weChatClient.getPhoneNumber(accessToken, code);
        return success(phoneNumber);
    }

}
